package com.itcodai.controller.thread;

import com.itcodai.entity.JsonResult;
import com.itcodai.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 线程池的使用
 *
 * @author jiejie
 * @date 2021/12/10
 * @apiNote
 */
@RestController
@RequestMapping("/threadpool")
public class ThreadPoolTestController {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolTestController.class);

    @Resource
    private AsyncService asyncService;

    @GetMapping("/async")
    public JsonResult async(Integer num) {
        if (num == null) {
            num = new Integer(20);
        }
        logger.info("开始执行异步任务 num-{}", num);
        for (int i = 0; i < num; i++) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            logger.info("任务-{} 开始执行", i);
            asyncService.executeAsync(i);
        }
        //logger.info("任务-{} 开始执行", 2);
        //asyncService.executeAsync(2);
        logger.info("执行异步任务结束！");
        return new JsonResult<>();
    }

}
